package org.ysling.litemall.wx.web;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import java.util.*;

import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ysling.litemall.core.utils.JacksonUtil;
import org.ysling.litemall.core.utils.ResponseUtil;
import org.ysling.litemall.core.validator.Order;
import org.ysling.litemall.core.validator.Sort;
import org.ysling.litemall.db.domain.LitemallCollect;
import org.ysling.litemall.db.domain.LitemallGoods;
import org.ysling.litemall.db.domain.LitemallTopic;
import org.ysling.litemall.db.service.LitemallCollectService;
import org.ysling.litemall.db.service.LitemallGoodsService;
import org.ysling.litemall.db.service.LitemallTopicService;
import org.ysling.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户收藏服务
 */
@RestController
@RequestMapping("/wx/collect")
@Validated
public class WxCollectController {
    private final Log logger = LogFactory.getLog(WxCollectController.class);

    @Autowired
    private LitemallCollectService collectService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallTopicService topicService;

    /**
     * 用户收藏列表
     *
     * @param userId 用户ID
     * @param type   类型，如果是0则是商品收藏，如果是1则是专题收藏
     * @param page   分页页数
     * @param limit   分页大小
     * @return 用户收藏列表
     */
    @GetMapping("list")
    public Object list(@LoginUser Integer userId,
                       @NotNull Byte type,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.okList(collectService.queryByType(userId, type, page, limit, sort, order));
    }

    /**
     * 用户收藏添加或删除
     * <p>
     * 如果商品没有收藏，则添加收藏；如果商品已经收藏，则删除收藏状态。
     *
     * @param userId 用户ID
     * @param body   请求内容，{ type: xxx, valueId: xxx }
     * @return 操作结果
     */
    @PostMapping("addordelete")
    public Object addOrDelete(@LoginUser Integer userId, @RequestBody String body) {
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }

        Byte type = JacksonUtil.parseByte(body, "type");
        Integer valueId = JacksonUtil.parseInteger(body, "valueId");
        if (!ObjectUtils.allNotNull(type, valueId)) {
            return ResponseUtil.badArgument();
        }

        LitemallCollect collect = collectService.queryByTypeAndValue(userId, type, valueId);
        if (collect != null) {
            collectService.deleteById(collect.getId());
        } else {
            collect = new LitemallCollect();
            if (Objects.equals(type , Byte.parseByte("0"))){
                //商品收藏
                LitemallGoods goods = goodsService.findById(valueId);
                if (goods == null) return ResponseUtil.badArgument();
                collect.setPicUrl(goods.getPicUrl());
                collect.setName(goods.getName());
                collect.setBrief(goods.getBrief());
                collect.setPrice(goods.getRetailPrice());
            } else if (Objects.equals(type , Byte.parseByte("1"))){
                //专题收藏
                LitemallTopic topic = topicService.findById(valueId);
                if (topic == null) return ResponseUtil.badArgument();
                collect.setPicUrl(topic.getPicUrl());
                collect.setName(topic.getTitle());
                collect.setBrief(topic.getSubtitle());
                collect.setPrice(topic.getPrice());
            } else {
                return ResponseUtil.badArgument();
            }

            collect.setUserId(userId);
            collect.setValueId(valueId);
            collect.setType(type);
            collectService.add(collect);
        }

        return ResponseUtil.ok();
    }
}